package com.hqhy.like.stock.service.impl;

import com.hqhy.like.common.enumerator.ServiceCode;
import com.hqhy.like.common.ex.ServiceException;
import com.hqhy.like.stock.dao.persist.mapper.TableMapper;
import com.hqhy.like.stock.pojo.entity.Table;
import com.hqhy.like.stock.service.ITableService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.hqhy.like.common.consts.data.CommonConsts.*;

@Slf4j
@Service
public class TableServiceImpl implements ITableService {

    @Autowired
    private TableMapper tableMapper;

    @Override
    public List<Table> list() {
        return tableMapper.list();
    }

    /**
     * 修改用户的启用状态
     *
     * @param id     用户ID
     * @param enable 新的启用状态
     */
    private void updateEnableById(Long id, Integer enable) {
        log.debug("开始处理【{}用户】的业务，ID：{}，目标状态：{}", ENABLE_STATE_TEXT[enable], id, enable);

        Table table = tableMapper.selectById(id);
        if (table == null) {
            String message = ENABLE_STATE_TEXT[enable] + "桌台失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }

        if (table.getIsEnable().equals(enable)) {
            String message = ENABLE_STATE_TEXT[enable] + "桌台失败，当前用户已经处于"
                    + ENABLE_STATE_TEXT[enable] + "状态！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
        }

        Table user = new Table();
        user.setId(id);
        user.setIsEnable(enable);
        int rows = tableMapper.updateById(user);
        if (rows != 1) {
            String message = ENABLE_STATE_TEXT[enable] + "服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }

    }

    @Override
    public void setEnable(Long userId) {
        log.debug("开始处理【启用桌台】的业务，参数：{}", userId);
        updateEnableById(userId, ENABLE_STATE_ON);
    }

    @Override
    public void setDisable(Long userId) {
        log.debug("开始处理【禁用桌台】的业务，参数：{}", userId);
        updateEnableById(userId, ENABLE_STATE_OFF);
    }

    @Override
    public void addNew(Table table) {
        log.debug("开始处理【添加桌台】的业务，参数：{}", table);
        // 检查用户名是否被占用
        String tableName = table.getTableName();
        int count = tableMapper.countByUsername(tableName);
        if (count > 0) {
            String message = "添加桌台失败，桌台名已经被占用！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
        }
        table.setIsEnable(0);
        table.setIsAvailable(0);
        tableMapper.insert(table);
    }

    @Override
    public void delete(Long id) {
        tableMapper.deleteById(id);
    }
}
